#==================================================
#	Node Added
#==================================================
#   节点树添加了节点
# * 使用时调用 set_editor_plugin 或 set_editor_interface
#    并连接这个对象的 node_added 信号即可
# * 因为在编辑器中 get_tree 的 node_added 信号也会发出 
#    Inspector 中更换的节点，所以要通过个对象做个过滤
#==================================================
# @datetime: 2021-9-1 23:28:23
#==================================================

extends Reference


## 新添加的节点
signal node_added(node)


const MetaAddedNodeKey = "@node_is_added"


var _editor_plugin : EditorPlugin setget set_editor_plugin, get_editor_plugin
var _editor_interface : EditorInterface setget set_editor_interface, get_editor_interface
var _tree : SceneTree setget , get_tree

var _is_yield := false
var _yield_added_node_list := []



#==================================================
#   Set/Get
#==================================================
func set_editor_plugin(value: EditorPlugin) -> void:
	_editor_plugin = value
	set_editor_interface(_editor_plugin.get_editor_interface())

func get_editor_plugin() -> EditorPlugin:
	return _editor_plugin

func set_editor_interface(value: EditorInterface) -> void:
	_editor_interface = value
	_tree = _editor_interface.get_tree()
	if not _tree.is_connected("node_added", self, "_node_added"):
		_tree.connect("node_added", self, "_node_added")

func get_editor_interface() -> EditorInterface:
	return _editor_interface

func get_tree() -> SceneTree:
	return _tree



#==================================================
#   自定义方法
#==================================================
func _node_added(added_node: Node) -> void:
	_yield_added_node_list.push_back(added_node)
	
	# 一帧执行后面方法一次
	if _is_yield:
		return
	else:
		_is_yield = true
		yield(get_tree(), "physics_frame")
	_is_yield = false
	
	# 过滤非编辑的场景树的节点
	for node in _yield_added_node_list:
		if (
			is_instance_valid(node) 
			&& node.owner
			&& not node.has_meta(MetaAddedNodeKey)
		):
			# 标记节点已经添加到过场景中
			node.set_meta(MetaAddedNodeKey, true)
			# 发出信号
			emit_signal("node_added", node)
	
	# 清空上次 yield 记录的节点
	_yield_added_node_list.clear()

